package com.sduept.nwld.dataserver.rest;

import com.alibaba.fastjson.JSONObject;
import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.manager.countanalyse.ProtectAnalysisManger;
import com.sduept.nwld.dataserver.model.countanalyse.CountProtectDefect;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 缺陷分析数据rest
 *
 */
@RestController
@RequestMapping("/defect")
public class DefectAnalysisService {
	@Autowired
	private SuperDAO dao;
	@Autowired
	private ProtectAnalysisManger pa;

	/**
	 * 根据年获得缺陷分析
	 * 
	 * @param year
	 * @return {}
	 */
	//
	//@GetMapping("/getDefectAnalysisByYear/{year}")
	public String getDefectAnalysisByYear(@PathVariable("year") String year) {
		String rtn = "{count:1291,"
				+ "reality:1197,"
				+ "rate:'92.72%',"
				+ "timelyRate:'99.30%',"
				+ "category:[[ '紧急缺陷',78], ['重大缺陷',457], ['一般缺陷',756]],"
				+ "device:[[ '断路器保护',52],[ '保信系统',50],[ '线路保护',364], ['母线保护',66],['变压器保护',180],[ '其它',223],[ '故障录波器',372]],"
				+ "province:{"
				+ "lables:['超高压公司', '调峰调频公司', '广东电网', '广西电网', '云南电网', '贵州电网', '海南电网',	'广州电网', '深圳电网' ],"
				+ "values:[24,14,345,127,187,253,45,159,137]"
				+ "},"
				+ "details:["
				+ "{name:'保护装置缺陷',count:1000,rate:'77.46%',"
				+ "values:["
				+ "[['CPU板',204],['开入板',26],['交流板',47],['管理板',69],['液晶显示板',95],['电源板',146],['其他',352]],"
				+ "[['元器件损坏',702],['接触不良',25],['软故障',199],['通道异常',1],['电源板',146],['其他',352],['接口接触不良',3],['保护外部回路元件损坏',15]]"
				+ "]},"
				+ "{name:'二次回路缺陷',count:194,rate:'15.03%',"
				+ "values:["
				+ "[['二次回路',95],['其他',95],['空气开关或保险',3],['尾纤',1]],"
				+ "[['接口接触不良',1],['其他',1],['光纤断纤',1],['接触不良',55],['回路接错',4],['保护外部回路元件损坏',132]]"
				+ "]},"
				+ "{name:'保护通道缺陷',count:97,rate:'7.51%',"
				+ "values:["
				+ "[['光缆',18],['通信设备',30],['其它',22],['尾纤',11],['光纤接头',16]],"
				+ "[['接口接触不良',1],['其他',1],['通道异常',52],['软故障',8],['光纤断纤',9],['接触不良',12],['高频通道衰耗变化',1],['保护外部回路元件损坏',2]]"
				+ "]}" + "]}";

		return JSONObject.parse(rtn).toString();
	}


	@GetMapping("/getDefectAnalysisByYear/{year}")
	public String getDefectAnalysisByYear1(@PathVariable("year") String year) {
		DecimalFormat df=new DecimalFormat("#0.00");
		JSONObject jso = new JSONObject();
		List<CountProtectDefect> pdList = pa.getCountProtectDefectByYear(year);
			jso.put("count", pdList.size());
			int solve = 0;// 消缺个数
			int timelySolve = 0;// 及时消缺个数
			List<List<String>> levelList = new ArrayList<>();// 缺陷等级list
			List<List<String>> deviceList = new ArrayList<>();// 缺陷装置list
			Map<String, List<String>> provinceMap = new HashMap<>();// 缺陷省区map
			List<String> namelist = new ArrayList<>();
			List<String> valuelist = new ArrayList<>();
			provinceMap.put("lables", namelist);
			provinceMap.put("values", valuelist);
			// 详细信息
			Map<String, List<CountProtectDefect>> allDefectType = pa.getCountProtectDefectByType(pdList);
			JSONArray arr = getDetailsMap(allDefectType, pdList);
			// 分类
			for (CountProtectDefect pd : pdList) {
				if (pd.getSolveDate() != null) {
					solve++;
					//TODO  pd.getSpecifiedSolveDate()  为空报错
					if(pd.getSpecifiedSolveDate()==null || pd.getSolveDate().before(pd.getSpecifiedSolveDate())){
		            	timelySolve++;
		            }
				}
				if (pd.getDefectLevel() != null) {
					levelList = getDefectList(pd.getDefectLevel()+"缺陷", levelList);
				}
				if (pd.getDefectDevice() != null) {
					deviceList = getDefectList(pd.getDefectDevice(), deviceList);
				}
				if (pd.getProvince() != null) {
					provinceMap = getDefectProvinceMap(pd.getProvince(),
							provinceMap);
				}
			}
			jso.put("reality", solve);
			jso.put("category", levelList);
			jso.put("device", deviceList);
			jso.put("province", provinceMap);
			jso.put("details", arr);
			if(pdList.size()>0) {
				jso.put("rate", df.format(((double)solve / (double)pdList.size())*100)+"%");
				jso.put("timelyRate", df.format(((double)timelySolve / (double)pdList.size())*100)+"%");
			} else {
				jso.put("rate","0.00%");
				jso.put("timelyRate", "0.00%");
			}
		return jso.toJSONString();
	}

	// 获取缺陷等级和缺陷设备list
	// 返回的结果为[[name,value],[name,value]]
	private List<List<String>> getDefectList(String comparedParam,
			List<List<String>> resultList) {
		// 缺陷等级
		if (resultList.size() == 0) {
			List<String> list = new ArrayList<>();
			list.add(comparedParam);
			list.add("1");
			resultList.add(list);
		} else {
			int i = 0;
			for (List<String> list : resultList) {
				i++;
				if (comparedParam.equals(list.get(0))) {
					list.set(1, Integer.parseInt(list.get(1)) + 1 + "");
					break;
				}
				if (i == resultList.size()) {
					List<String> newList = new ArrayList<>();
					newList.add(comparedParam);
					newList.add("1");
					resultList.add(newList);
					break;
				}
			}
		}
		return resultList;
	}

	// 获取缺陷省区
	private Map<String, List<String>> getDefectProvinceMap(
			String comparedParam, Map<String, List<String>> map) {
		List<String> lables = map.get("lables");
		List<String> values = map.get("values");
		if (lables.size() == 0) {
			lables.add(comparedParam);
			values.add("1");
		}else{
			for (int i = 0; i < lables.size(); i++) {
				if (comparedParam.equals(lables.get(i))) {
					values.set(i, Integer.parseInt(values.get(i)) + 1 + "");
					break;
				}
				if (i == lables.size() - 1) {
					lables.add(comparedParam);
					values.add("1");
					break;
				}
			}
		}
		return map;
	}

	// 详细信息
	private JSONArray getDetailsMap(Map<String, List<CountProtectDefect>> allDefectType,List<CountProtectDefect> pdList) {
		DecimalFormat df=new DecimalFormat("#0.00");
		JSONArray arr = new JSONArray();
		for (Entry<String, List<CountProtectDefect>> entry : allDefectType.entrySet()) {
			JSONObject jsobject = new JSONObject();
			String type = entry.getKey();
			List<CountProtectDefect> defect = entry.getValue();
			jsobject.put("name", type);
			jsobject.put("count", defect.size());
			if(pdList.size()>0) {
				jsobject.put("rate", df.format(((double)defect.size()/(double)pdList.size())*100)+"%");
			} else {
				jsobject.put("rate", "0.00%");
			}
			List<List<String>> defectPos = new ArrayList<>();
			List<List<String>> defectCause = new ArrayList<>();
			for (CountProtectDefect d : defect) {
				if (d.getDefectPosition() != null) {
					defectPos = getDefectList(d.getDefectPosition(), defectPos);
				}
				if (d.getDefectCause() != null) {
					defectCause = getDefectList(d.getDefectCause(), defectCause);
				}
			}
			List<List<List<String>>> value = new ArrayList<>();
			value.add(defectPos);
			value.add(defectCause);
			jsobject.put("values", value);
			arr.add(jsobject);
		}
		return arr;
	}

}
